"""
 This module mainly exists for the MySpace iGoogle gadget demo
 When the user requests http://<hostname>/ig, it sets the user name as "demouser"
 and sets up a subscription via the following callback url: 
 http://<hostname>/subscriber.demouser

 Client updates will be requested by invoking http://<hostname>/getupdates
 (which will be handled by GetUpdatesHandler in msflood.py)

An iGoogle gadget module definition looks like this:

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="MySpace Realtime Activity Updates" height="400"/>
  <Content type="url" href="http://ms-flood.appspot.com/ig" />
</Module>

Assuming the gadget spec above is stored @ http://cnanga.com/flood.xml 
it can be added to iGoogle by using the following url:

    http://www.google.com/ig/adde?moduleurl=http://cnanga.com/flood.xml&source=imag
"""

import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import simplejson
import gmemsess
import ckeynsecret

from myspace.myspaceapi import MySpace
from usersession import User
from models import Subscription, RawFeed

class IGoogleHandler(webapp.RequestHandler):
    user_id = "demouser"
    
    def get(self):
        self.show_main_page()

    def show_main_page(self):
        self.check_subscription()                

        session=gmemsess.Session(self)
        User.set_current_user(self, self.user_id, self.user_id)
        
        path = os.path.join(os.path.dirname(__file__), 'templates/igoogle.html')
        return self.response.out.write(template.render(path, {}))
    
    """ Checks to see if a subscription has been setup or not
        Makes a subscription request if one's not already present in the datastore
    """
    def check_subscription(self):
        subscription = Subscription.get_user_subscription(self.user_id)
        if subscription:
            return True
        else:
            callback_url = self.request.host_url + "/subscriber." + self.user_id
            subscription_payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"\
                                "<Subscription>"\
                                "<Type>All</Type>" \
                                "<Endpoint><![CDATA[" + callback_url + "]]></Endpoint>"\
                                "<Query></Query>"\
                                "<MetaData>UserInfo,UserSubscribers,ApplicationData</MetaData>"\
                                "<BatchSize>1</BatchSize>"\
                                "<Rate>5</Rate>"\
                                "<Format><![CDATA[application/atom+xml]]></Format>"\
                                "</Subscription>"
            return self.perform_subscription(subscription_payload)
    
    def perform_subscription(self, query_xml):
        ms = MySpace(ckeynsecret.CONSUMER_KEY, ckeynsecret.CONSUMER_SECRET)
        status,subscription_id = ms.register_subscription(query_xml)
        if status == 201:
           subscription = Subscription(user=self.user_id, ms_subscription_id=subscription_id)
           subscription.put()
           